<?php

namespace app\admin\controller;

use think\facade\Session;
use app\admin\controller\Base;
use app\admin\model\Member;
use app\admin\model\AuthGroup as GroupModel;

class Personal extends Base
{
    public function initialize()
    {
        parent::initialize();
        $this->Model = new Member();
    }

    // 修改个人信息
    public function update(){
        $id = login_member_id();
        $member = $this->Model->findOne($id);
        if($this->request->isPost()){
            $fields = [
                ['name' => 'email', 'type' => 'string', 'default' => ''],
                ['name' => 'mobile', 'type' => 'string', 'default' => ''],
                ['name' => 'gender', 'type' => 'string', 'default' => ''],
                ['name' => 'avatar', 'type' => 'string', 'default' => $member['avatar']],
                // ['name' => 'birthday', 'type' => 'string', 'default' => NULL],
            ];

            $data = $this->parsePostParam($fields, ['id' => $id]);
            $res = $this->Model->updateItem($data);
            $this->Model->reloadLoginInfo($id);
            if($res['status']){
                Session::flash('success', $res['msg']);
                $this->success($res['msg'], 'update');
            }else{
                Session::flash('danger', $res['msg']);
                $this->error($res['msg']);
            }
        }else{
          $this->assign("member", $member);
          return $this->fetch();
        }
    }

    // 修改登录密码
    public function change_password(){
        $id = login_member_id();
        if($this->request->isPost()){
            $fields = [
                ['name' => 'old_password', 'type' => 'string', 'default' => ''],
                ['name' => 'password', 'type' => 'string', 'default' => ''],
                ['name' => 'confirm_password', 'type' => 'string', 'default' => ''],
            ];

            $data = $this->parsePostParam($fields, ['id' => $id]);
            $res = $this->Model->changePassword($data);
            if($res["status"]){
                Session::flash('success', $res['msg']);
                $this->success($res["msg"], "change_password");
            }else{
                Session::flash('danger', $res['msg']);
                $this->error($res["msg"]);
            }
        }else{
            return $this->fetch();
        }
    }

    //验证用户登录密码
    public function ajax_valid_password(){
        $password = $this->request->post("old_password");
        $id = login_member_id();
        $valid_res = $this->Model->validPassword($id, $password);
        echo($valid_res);
    }
}
